package com.my.ycv51.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.my.ycv51.R;
import com.my.ycv51.constant.MMKVConstant;
import com.my.ycv51.dialog.CheckFaceDialogTwo;
import com.my.ycv51.dialog.RegistFaceDialog;
import com.my.ycv51.dialog.RegistFaceDialogTwo;
import com.my.ycv51.util.LogUtil;
import com.my.ycv51.util.MMKVUtil;

public class CheckActivity extends AppCompatActivity {
    private int count = 0;
    private int reigstCount = 0;
    private TextView tvCount, tvRegistCount;
    private String[] requirePermissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    private static final int PERMISSION_REQUEST_CODE = 1000;
    private boolean havePermission = false;

    private CheckFaceDialogTwo checkFaceDialog;


    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check);

//        EventBus.getDefault().register(this);

        initView();
    }


    @Override
    protected void onResume() {
        super.onResume();
        processPermission(); // 申请权限
    }

    /**
     * The next code is that requests permission from user
     */
    private void processPermission() {
        LogUtil.e("检验相机和文件权限");
        boolean allGranted = checkPermissionAllGranted(requirePermissions);

        if (!allGranted) {
            LogUtil.e("申请相机和文件权限");
            havePermission = false;
            ActivityCompat.requestPermissions(this, requirePermissions, PERMISSION_REQUEST_CODE);
        } else {
            havePermission = true;
            LogUtil.e("拥有相机和文件权限");
            // 拥有权限
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;
            for (int granted : grantResults) {
                if (granted != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (isAllGranted) {
                LogUtil.e("赋予了相机和文件权限");
                havePermission = true;
            } else {
                havePermission = false;
                Toast.makeText(this, "禁止权限可能导致程序无法正常运行，请到设置-应用打开相应权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean checkPermissionAllGranted(String[] permissions) {
        if (permissions != null) {
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }


    private void initView() {
        tvCount = findViewById(R.id.tv_count);
        tvRegistCount = findViewById(R.id.tv_regist_count);

        findViewById(R.id.btn_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (havePermission) {
                    goRegister();
                } else {
                    processPermission();
                }
            }
        });

        findViewById(R.id.btn_check_face).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (havePermission) {
                    goCheck();
                } else {
                    processPermission();
                }
            }
        });
    }

    /**
     * 检测人脸
     */
    private void goCheck() {
        LogUtil.e("获取人脸数据：" + MMKVUtil.getInstance().decodeString(MMKVConstant.REGIST_FACE));
        String userFace = MMKVUtil.getInstance().decodeString(MMKVConstant.REGIST_FACE);

        if (userFace == null || userFace.isEmpty()) {
            Toast.makeText(this, "没有录入人脸信息", Toast.LENGTH_SHORT).show();
            return;
        }

//        CheckFaceDialog checkFaceDialog = new CheckFaceDialog(this, userFace, new CheckFaceDialog.DialogCallBack() {
//            @Override
//            public void onCancle() {
//
//            }
//
//            @Override
//            public void showMessage(String msg) {
//
//            }
//
//            @Override
//            public void checkSuccess() {
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        count++;
//                        Toast.makeText(CheckActivity.this, "验证成功!", Toast.LENGTH_SHORT).show();
//                        LogUtil.e("第" + count + "次执行");
//                        tvCount.setText("已执行：" + count + "次");
//                        goCheck();
//                    }
//                }, 1000);
//            }
//        });
//
//        checkFaceDialog.show();

//        CheckFaceDialogTwo checkFaceDialog = new CheckFaceDialogTwo(this, userFace, new CheckFaceDialogTwo.DialogCallBack() {
        checkFaceDialog = new CheckFaceDialogTwo(this, userFace, new CheckFaceDialogTwo.DialogCallBack() {
            @Override
            public void onCancle() {

            }

            @Override
            public void showMessage(String msg) {

            }

            @Override
            public void checkSuccess() {
                Toast.makeText(CheckActivity.this, "验证成功!", Toast.LENGTH_SHORT).show();

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        count++;
                        LogUtil.e("第" + count + "次执行");
                        tvCount.setText("验证已执行：" + count + "次");
                        goCheck();
                    }
                }, 1000);
            }
        });

        checkFaceDialog.show();
    }

    /**
     * 注册人脸
     */
    private void goRegister() {
//        RegistFaceDialog inputFaceDialog = new RegistFaceDialog(this, new RegistFaceDialog.DialogCallBack() {
//            @Override
//            public void onCancle() {
//
//            }
//
//            @Override
//            public void showMessage(String msg) {
//
//            }
//
//            @Override
//            public void inputSuccess(String face) {
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        LogUtil.e("存储人脸特征：" + face);
//                        // 存储人脸信息
//                        MMKVUtil.getInstance().encode(MMKVConstant.REGIST_FACE, face);
//                        Toast.makeText(CheckActivity.this, "录入成功", Toast.LENGTH_SHORT).show();
//                    }
//                });
//            }
//        });
//
//        inputFaceDialog.show();

        RegistFaceDialogTwo registFaceDialogTwo = new RegistFaceDialogTwo(this, new RegistFaceDialogTwo.DialogCallBack() {
            @Override
            public void onCancle() {

            }

            @Override
            public void showMessage(String msg) {

            }

            @Override
            public void inputSuccess(String face) {
                // 存储人脸信息
                MMKVUtil.getInstance().encode(MMKVConstant.REGIST_FACE, face);
                Toast.makeText(CheckActivity.this, "录入成功", Toast.LENGTH_SHORT).show();

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        reigstCount++;
                        LogUtil.e("录入第" + reigstCount + "次执行");
                        tvRegistCount.setText("录入已执行：" + reigstCount + "次");
                        goRegister();
                    }
                }, 1000);
            }
        });

        registFaceDialogTwo.show();
    }

    @Override
    protected void onDestroy() {
//        EventBus.getDefault().removeAllStickyEvents();
//        EventBus.getDefault().unregister(this);
        super.onDestroy();

        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }

//    //处理普通事件
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void eventBus(SimpleEvent event) {
//
//        switch (event.getCode()) {
//            case 0: // msg
////                Toast.makeText(this, event.getMsg(), Toast.LENGTH_SHORT).show();
//                break;
//            case 1: // 成功
//                if (checkFaceDialog != null) {
//                    checkFaceDialog.closeDialog();
//                }
//                break;
//            case 2: // 失败
//                break;
//        }
//    }
}